import gdata.docs.data
import gdata.docs.client
import gdata.spreadsheet.service
import sys, os
from optparse import OptionParser
from getpass import getpass

p = OptionParser()
p.add_option('-u', dest='user', help="Gmail account name")
p.add_option('-p', dest='password', help="Gmail password")
p.add_option('-d', dest='dir', help="Directory to be saved")
p.add_option('-n', dest='name', default='template', help="Account name")
p.add_option('-v', dest='ver', help='Version')
(opt, args) = p.parse_args()

if not opt.password:
  opt.password = getpass("Enter the password: ")

if not (opt.user and opt.password and opt.dir and opt.name and opt.ver):
  print >>sys.stderr, "Need at least -u -d -n -v"
  p.print_help()
  sys.exit(0)

csheet = gdata.spreadsheet.service.SpreadsheetsService()
csheet.email = opt.user
csheet.password = opt.password
csheet.ProgrammaticLogin()
cdoc = gdata.docs.client.DocsClient()
cdoc.ssl = True
cdoc.ClientLogin(email=opt.user, password=opt.password, source='uoit-pages')

if not os.path.exists(opt.dir):
  os.makedirs(opt.dir)

# Get the folder
folder = None
foldername = "pages - %s - %s" % (opt.name, opt.ver)
for f in cdoc.GetDocList(uri="/feeds/default/private/full/-/folder").entry:
  if f.title.text == foldername:
    folder = f
    break

if not folder:
  print 'Folder "%s" is not found' % foldername
  sys.exit(0)

# Start downloading: need to exchange auth_token between two clients
# and switch back when done.
feed = cdoc.GetDocList(uri=folder.content.src)
cs_token = csheet.GetClientLoginToken()
cd_token, cdoc.auth_token.token_string = cdoc.auth_token.token_string, cs_token

for e in feed.entry:
  filename = "%s.xls" % e.title.text
  print filename,
  cdoc.Export(e, os.path.join(opt.dir, filename))
  print "downloaded"

cdoc.auth_token.token_string = cd_token
